import { Injectable } from '@nestjs/common';
import { createClient, RedisClientType } from 'redis';
import Constant from 'src/config/Constant';

const r = Constant.redisConfig

@Injectable()
export class RedisServer {
  redisService: RedisClientType;
  private _redisClient: RedisClientType | undefined;

  async getClient(): Promise<RedisClientType> {
    if (this._redisClient) {
      return this._redisClient;
    }

    const client = createClient({
      url: `redis://:${r.password}@${r.host}:${r.port}/0`,
    });

    client.on('error', (err: any) => {
      throw new Error('redis 链接失败' + JSON.stringify(err));
    });

    await client.connect();

    this._redisClient = client as RedisClientType;

    return this._redisClient;
  }
}
